/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.CommonUtil;
import Common.Global;
import java.util.Calendar;
import java.util.Date;


import java.util.Timer;
import java.util.TimerTask;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

/**
 *
 * @author NamDH
 */
public class ServletContextListener implements javax.servlet.ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        ServletContext servletContext = arg0.getServletContext();
        System.out.println("*********ServletContextListener started*********");

        int delay = 1000;


        Global.timeInterval = Integer.parseInt(CommonUtil.readProperties(Global.timePropName));

        if(CommonUtil.readProperties("radio").equals("auto")){
              Global.timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
 
                CommonUtil.updateInfo();
            }//End of Run
        }, delay, Global.timeInterval*1000);
        }
      
        servletContext.setAttribute("timer", Global.timer);


        //get specific time

        Calendar calendar = Calendar.getInstance();
         calendar.set(Calendar.DAY_OF_WEEK, Integer.parseInt(CommonUtil.readProperties("dayofweek"))); //
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(CommonUtil.readProperties("hourofday")));
        calendar.set(Calendar.MINUTE, Integer.parseInt(CommonUtil.readProperties("minuteofhour")));
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();

        Timer timer2 = new Timer();
        //run function at specific time
        timer2.schedule(new TimerTask(){
            public void run(){
                CommonUtil.sendEmailWeekend();
            }
        }, time);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContextListener destroyed");
    }
}
